package com.partner.share.work.websocket.server;

import com.partner.share.work.websocket.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author pengyangyan
 */
@Slf4j
@ServerEndpoint(value = "/websocket/{user}")
@Component
public class WebsocketService {

    /**
     * 初始在线人数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     *  与某个客户端建立的连接会话
     */
    public static Session currentSession;

    /**
     * 当前用户
     */
    public String username;


    /**
     * 存储session
     */
    public static Map<String,Session> map = new ConcurrentHashMap<>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("user")String user, Session session) {
        username = user;
        currentSession = session;
        map.put(user,session);
        int count = onlineCount.incrementAndGet();
        log.info("有新的链接加入！当前在线人数: {}",count);
        broadcast(username+":大家好!");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        map.remove(username);
        onlineCount.decrementAndGet();
        log.info("有链接关闭,当前在线人数为: {}", map.size());
    }


    @OnMessage
    public void onMessage(String message,Session session){
        log.info("收到来自客户端的消息：{}",message);
        session.getAsyncRemote().sendText(message);
    }


    @OnError
    public void onError(Session session, Throwable error)  {
        log.error("WebSocket发生错误:{}",error.getMessage());
        error.printStackTrace();
    }

    /**
     * 获取在线用户数量
     *
     * @return 在线用户数量
     */
    public int getOnlineUserCount() {
        return onlineCount.get();
    }

    private String generateMessage(String message){
        return username+":"+message;
    }

    public void broadcast(String message){
        if (map.size()==0){
            return;
        }
        Collection<Session> values = map.values();
        Set<Session> sessions = new HashSet<>(values);
        String user = message.split(":")[0];

        sessions.forEach(session -> {
            try {
                synchronized(this){
                    session.getAsyncRemote().sendText(message);
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

}
